package chan.project.smartlaweveryman.service.impl;

import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.constant.CommonConstant;
import chan.project.smartlawcommon.constant.TokenConstant;
import chan.project.smartlawcommon.exception.BusinessException;
import chan.project.smartlawcommon.utils.SqlUtils;
import chan.project.smartlaweveryman.service.UserRoleService;
import chan.project.smartlaweveryman.strategy.RegisterManager;
import chan.project.smartlawmodel.dto.common.CommonInfoRegisterRequest;
import chan.project.smartlawmodel.dto.lawyer.LawyerInfoRegisterRequest;
import chan.project.smartlawmodel.dto.user.UserInfoQueryRequest;
import chan.project.smartlawmodel.dto.user.UserInfoRegisterRequest;
import chan.project.smartlawmodel.entity.CommonInfo;
import chan.project.smartlawmodel.entity.LawyerInfo;
import chan.project.smartlawmodel.entity.UserInfo;
import chan.project.smartlawmodel.entity.UserRole;
import chan.project.smartlawmodel.enums.UserRoleEnum;
import chan.project.smartlawmodel.vo.LoginUserVO;
import chan.project.smartlawmodel.vo.UserInfoVO;
import chan.project.smartlawservice.commonService.CommonInfoFeignClient;
import chan.project.smartlawservice.lawyerService.LawyerInfoFeignClient;
import chan.project.smartlawservice.lawyerService.LawyerInfoFeignClient;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import chan.project.smartlaweveryman.service.UserInfoService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import chan.project.smartlaweveryman.mapper.UserInfoMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static chan.project.smartlawcommon.constant.UserConstant.USER_LOGIN_STATE;


/**
* @author 彭科文
* @description 针对表【user_info(用户信息表)】的数据库操作Service实现
* @createDate 2025-06-15 10:30:50
*/
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{


    @Resource
    private UserRoleService userRoleService;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RegisterManager registerManager;

    @Resource
    private LawyerInfoFeignClient lawyerInfoFeignClient;

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "yupi";


    /**
     * 基本账号注册
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", userAccount);
            UserInfo userInfo = this.baseMapper.selectOne(queryWrapper);
            //已经存在基础账号
            if (ObjectUtil.isNotEmpty(userInfo)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            UserInfo user = new UserInfo();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            long userId = userInfoMapper.insert(user);
            return userId;
        }
    }

    /**
     * 普通用户注册
     * @param commonInfoRegisterRequest
     * @return
     */
    @Override
    @Transactional
    public long commonRegister(CommonInfoRegisterRequest commonInfoRegisterRequest){
        return registerManager.commonRegister(commonInfoRegisterRequest);
    }

    /**
     * 律师用户注册
     * @return
     */
    @Override
    public long lawyerRegister(LawyerInfoRegisterRequest lawyerInfoRegisterRequest){
        return registerManager.lawyerRegister(lawyerInfoRegisterRequest);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public UserInfo getLoginUser(HttpServletRequest request) {
        String userId = (String) StpUtil.getLoginId();
        if(ObjectUtil.isEmpty(userId)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户token异常");
        }
        UserInfo byId = this.getById(userId);
        if(ObjectUtil.isEmpty(byId)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"当前用户不存在");
        }
        return byId;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public UserInfo getLoginUserPermitNull(HttpServletRequest request) {
        //获取token
        String userId = (String) StpUtil.getLoginId();
        if(ObjectUtil.isEmpty(userId)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户token异常");
        }
        UserInfo byId = this.getById(userId);
        if(ObjectUtil.isEmpty(byId)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"当前用户不存在");
        }
        return byId;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        UserInfo loginUser = this.getLoginUser(request);
        return isAdmin(loginUser);
    }

    @Override
    public boolean isAdmin(UserInfo user) {
        return false;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        //获取token
        StpUtil.logout();
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(UserInfo user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserInfoVO getUserVO(UserInfo user) {
        if (user == null) {
            return null;
        }
        UserInfoVO userVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserInfoVO> getUserVO(List<UserInfo> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<UserInfo> getQueryWrapper(UserInfoQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "user_role", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "user_profile", userProfile);
        queryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public LoginUserVO baseUserLogin(String userAccount, String userPassword,String userRole) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        if(UserRoleEnum.getEnumByValue(userRole) == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户角色错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        UserInfo user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        //查看用户是否具有对应角色
        boolean hasRole = false;
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(String.valueOf(user.getId()), userRole);
        for (UserRole role : userRoleList) {
            Integer roleId = role.getRoleId();
            if(userRole.equals(String.valueOf(roleId)) || userRole.equals(UserRoleEnum.SUPER_ADMIN.getValue())){
                hasRole = true;
                break;
            }
        }
        if(!hasRole){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户权限不足");
        }
        //sa-token登录操作
        SaLoginParameter saLoginParameter = new SaLoginParameter();
        saLoginParameter.setExtra("role", userRole);
        StpUtil.login(user.getId(),saLoginParameter);
        LoginUserVO loginUserVO = this.getLoginUserVO(user);
        return loginUserVO;
    }

    /**
     * 普通用户登录
     * @param userAccount
     * @param userPassword
     * @return
     */
    @Override
    public LoginUserVO commonUserLogin(String userAccount, String userPassword){
        return baseUserLogin(userAccount, userPassword, UserRoleEnum.USER.getValue());
    }

    /**
     * 律师用户登录
     * @param userAccount
     * @param userPassword
     * @return
     */
    @Override
    public LoginUserVO lawyerUserLogin(String userAccount, String userPassword){
        return baseUserLogin(userAccount, userPassword, UserRoleEnum.LAWYER.getValue());
    }

}



